﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Web;
using VkontakteSharp.Model;

namespace VkontakteSharp.Endpoints.Execute
{
    public class Authenticated : VkontakteAPI
    {
        public Authenticated(VkontakteConfig config, string authInfo) : base(config, authInfo, "/execute") { }

        public Response<List<string>> Execute(string code)
        {
            return Execute<string>(code);
        }

        public Response<List<T>> Execute<T>(string code)
        {
            var jsOn = ExecuteJSON(code);
            if (jsOn.StartsWith("error", true, CultureInfo.CurrentCulture))
            {
                return new Response<List<T>>{Data = null,Error = new VkError
                {
                    Code = 0, Message = "Unknown error"
                }};
            }
            return (Response<List<T>>)Mapper.Map<Response<List<T>>>(jsOn);
        }

        private string ExecuteJSON(string code)
        {
            if (String.IsNullOrEmpty(code) || !code.Contains("return"))
            {
                throw new ArgumentOutOfRangeException("code", "Something wrong");
            }
            string uri = string.Format(base.Uri + "?v=5.5&access_token={0}&code={1}",
                AuthInfo, HttpUtility.UrlEncode(code)
                );
            return HttpClientOld.GET(uri);
        }

    }
}
